package drone.iqgc.controller ;

import java.awt.image.BufferedImage ;
import java.io.ByteArrayOutputStream ;
import java.io.InputStream ;
import java.io.OutputStream ;

import javax.imageio.ImageIO ;

import org.springframework.core.io.ClassPathResource ;
import org.springframework.core.io.DefaultResourceLoader ;
import org.springframework.stereotype.Controller ;
import org.springframework.web.bind.annotation.RequestMapping ;
import org.springframework.web.bind.annotation.ResponseBody ;

import drone.basis.base.BaseController ;
import drone.basis.util.QrcodeUtil ;
import drone.iqgc.config.HostConfig ;

@Controller
public class MainController extends BaseController
{

	public MainController ( )
	{
		super ( "" ) ;
	}

	@RequestMapping ( "favicon.ico" )
	public String favicon ( ) throws Exception
	{
		return "forward:/images/favicon.ico" ;
	}

	@RequestMapping (
	{
			"" ,
			"index"
	} )
	public String index ( ) throws Exception
	{
		return "redirect:main" ;
	}

	@RequestMapping ( "main" )
	public String main ( ) throws Exception
	{

		if ( new DefaultResourceLoader ( ).getResource ( DefaultResourceLoader.CLASSPATH_URL_PREFIX + "templates/" + peer ( ) + "/" + HostConfig.DOMAIN + ".html" ).exists ( ) )
		{
			return peer ( ) + "/" + HostConfig.DOMAIN ;
		}

		return peer ( ) + "/main" ;
	}
	
	@RequestMapping ( "test" )
	public String test ( ) throws Exception
	{
		return peer ( ) + "/test" ;
	}

	@RequestMapping ( "qrcode" )
	@ResponseBody
	public void qrcode ( ) throws Exception
	{

		try
		{
			InputStream logo = new ClassPathResource ( "/static/images/logo.jpg" ).getInputStream ( ) ;

			BufferedImage bufferedImage = QrcodeUtil.createImage ( HostConfig.DRONE_IQGC , logo , false ) ;
			ByteArrayOutputStream out = new ByteArrayOutputStream ( ) ;
			ImageIO.write ( bufferedImage , "jpg" , out ) ;

			byte [ ] data = out.toByteArray ( ) ;
			response.setContentType ( "image/jpeg" ) ;
			response.setHeader ( "Content-Disposition" , "attachment; filename=\"logo.jpg\"" ) ;
			response.setContentLength ( data.length ) ;
			response.setHeader ( "Content-Range" , "" + Integer.valueOf ( data.length - 1 ) ) ;
			response.setHeader ( "Accept-Ranges" , "bytes" ) ;
			OutputStream os = response.getOutputStream ( ) ;

			os.write ( data ) ;
			os.flush ( ) ;
			os.close ( ) ;

		} catch ( Exception e )
		{
			e.printStackTrace ( ) ;
			return ;
		}

	}

}
